package com.zbangmall.common;


import com.alipay.api.internal.util.StringUtils;
import com.zbangmall.wechat.domain.WechatMsg;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WechatUtil {

	public static WechatMsg map2Bean(Map<String, String> map) {
		WechatMsg msg = new WechatMsg();
		msg.setToUserName(map.get("ToUserName"));
		msg.setFromUserName(map.get("FromUserName"));
		msg.setCreateTime(System.currentTimeMillis());
		msg.setMsgType(map.get("MsgType"));
		msg.setContent(map.get("Content"));
		msg.setMsgId(map.get("MsgId"));
		return msg;
	}

	public static String checkSignature(Map<String, String[]> requestMap) {
		String nonce     = WechatUtil.getParam(requestMap.get("nonce"));
		String echostr   = WechatUtil.getParam(requestMap.get("echostr"));
		String signature = WechatUtil.getParam(requestMap.get("signature"));
		String timestamp = WechatUtil.getParam(requestMap.get("timestamp"));

		if (StringUtils.isEmpty(nonce) || StringUtils.isEmpty(echostr) || StringUtils.isEmpty(signature) || StringUtils.isEmpty(timestamp)) {
			return null;
		}

		String[] arr = new String[]{PropertiesUtil.propsWechat.getProperty("wechat.token"), timestamp, nonce};
		Arrays.sort(arr);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < arr.length; i++) {
			sb.append(arr[i]);
		}
		String temp = getSha1(sb.toString());
		return signature.equals(temp) ? echostr : null;
	}


	public static String getSha1(String str) {

		char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));

			byte[] md    = mdTemp.digest();
			int    j     = md.length;
			char   buf[] = new char[j * 2];
			int    k     = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
			return null;
		}
	}


	public static Map<String, String> document2Map(Document document) {
		if (document == null) {
			return null;
		}

		Map<String, String> map = new HashMap<String, String>();
		try {
			Element       root = document.getRootElement();
			List<Element> list = root.elements();
			for (Element element : list) {
				map.put(element.getName(), element.getText());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	public static Document request2Document(HttpServletRequest request) {

		try {

			SAXReader   reader      = new SAXReader();
			InputStream inputStream = request.getInputStream();
			Document    document    = reader.read(inputStream);
			return document;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static String getParam(String[] param) {
		if (param == null || param.length <= 0) {
			return null;
		}
		return param[0].toString();
	}

	public static void PrintlnWeXml(String msg) {
		System.out.println("--------------我的服务器发出--------------------");
		System.out.println(msg);
		System.out.println("--------------我的服务器发出--------------------");
	}

	public static void PrintlnWxXml(Map<String, String[]> requestMap) {
		System.out.println("--------------微信服务器发来--------------------");
		if (requestMap.isEmpty()) {
			System.out.println("null");
		} else {
			for (Map.Entry<String, String[]> entry : requestMap.entrySet()) {
				System.out.println(entry.getKey() + "=" + getParam(entry.getValue()));
			}
		}
		System.out.println("--------------微信服务器发来--------------------");
	}

	public static void PrintlnWxXml(Document document) {
		System.out.println("--------------微信服务器发来--------------------");
		if (document == null) {
			System.out.println(document);
		} else {
			System.out.println(document.asXML());
		}
		System.out.println("--------------微信服务器发来--------------------");

	}
}
